package cn.tedu.smartos.activity.service.impl;

import cn.tedu.smartos.activity.mapper.ActivityMapper;
import cn.tedu.smartos.activity.pojo.dto.*;
import cn.tedu.smartos.activity.pojo.entity.Activity;
import cn.tedu.smartos.activity.pojo.entity.ActivityCategory;
import cn.tedu.smartos.activity.pojo.entity.ActivityParticipation;
import cn.tedu.smartos.activity.pojo.vo.ActivityCategoryVO;
import cn.tedu.smartos.activity.pojo.vo.ActivityVO;
import cn.tedu.smartos.activity.service.ActivityService;
import cn.tedu.smartos.base.exception.ServiceException;
import cn.tedu.smartos.base.response.JsonResult;
import cn.tedu.smartos.base.response.StatusCode;
import cn.tedu.smartos.baseuser.pojo.entity.User;
import cn.tedu.smartos.volunteer.mapper.VolunteerMapper;
import cn.tedu.smartos.volunteer.pojo.entity.VolunteerInfo;
import cn.tedu.smartos.volunteer.pojo.entity.VolunteerSchedule;
import cn.tedu.smartos.volunteer.pojo.vo.VolunteerInfoVO;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.github.xiaoymin.knife4j.core.util.CollectionUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.stream.Collectors;
import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class ActivityServiceImpl implements ActivityService {
    @Autowired
    private ActivityMapper activityMapper;

    @Override
    public PageInfo<ActivityVO> list(ActivityQuery query) {
        log.debug("开始处理【所有活动列表】的请求,参数{}", query);
        PageHelper.startPage(query.getPageNum(), query.getPageSize());
        List<ActivityVO> activityVOS = activityMapper.list(query);
        return new PageInfo<>(activityVOS);
    }

    @Override
    public List<ActivityVO> getMyActivities(String username) {
        log.debug("开始处理【获取我的活动】的业务，参数：{}", username);
        User user = activityMapper.selectUserByUsername(username);
        if (user == null) {
            throw new ServiceException(StatusCode.USER_NOT_EXIT);
        }

        List<ActivityVO> myActivities = activityMapper.selectActivitiesByUserId(user.getUserId());

        return myActivities.stream().map(activity -> {
            ActivityVO vo = new ActivityVO();
            BeanUtils.copyProperties(activity, vo);
            return vo;
        }).collect(Collectors.toList());
    }

    @Override
    public ActivityVO detail(Long activityId) {
        log.debug("开始处理【获取活动详情】的业务，参数：{}", activityId);
        if (activityId == null) {
            throw new ServiceException("参数activityId不能为空");
        }
        ActivityVO activityVO = activityMapper.detail(activityId);
        return activityVO;
    }

    @Override
    public void delete(List<Long> activityIds) {
        log.debug("开始处理【删除活动】的请求,参数{}", activityIds);
        if (CollectionUtils.isEmpty(activityIds)) {
            throw new ServiceException("参数activityIds不能为空");
        }
        Integer rows = activityMapper.delete(activityIds);
        if (rows == 0) {
            throw new ServiceException("删除出错");
        }
        if (rows != activityIds.size()) {
            throw new ServiceException("部分活动删除失败");
        }
    }

    @Override
    public void update(ActivityUpdateParam updateParam) {
        log.debug("开始处理【修改活动】的请求,参数{}", updateParam);
        Activity activity = new Activity();
        BeanUtils.copyProperties(updateParam, activity);
        activity.setUpdateTime(new Date());
        Integer rows = activityMapper.update(activity);
        if (rows == 0) {
            throw new ServiceException("修改失败");
        }
    }

    @Override
    public void publish(ActivityAddParam addParam) {
        log.debug("开始处理【发布活动】的请求,参数{}", addParam);
        Activity activity = new Activity();
        BeanUtils.copyProperties(addParam, activity);
        activity.setCreateTime(new Date());
        activity.setUpdateTime(new Date());
        Integer rows = activityMapper.insert(activity);
        if (rows != 1) {
            throw new ServiceException("活动添加失败");
        }
    }

    @Override
    public PageInfo<ActivityVO> waitAudit(ActivityQuery query) {
        log.debug("开始处理【查询待审核活动】的请求,参数{}", query);
        PageHelper.startPage(query.getPageNum(), query.getPageSize());
        List<ActivityVO> activityVOS = activityMapper.waitAudit(query);
        return new PageInfo<>(activityVOS);
    }

    @Override
    public void addCategory(ActivityCategory activityCategory) {
        log.debug("开始处理【添加活动分类】的请求,参数{}", activityCategory);
        activityCategory.setCreateTime(new Date());
        Integer rows = activityMapper.insertCategory(activityCategory);
        if (rows != 1) {
            throw new ServiceException("添加活动分类失败");
        }
    }

    @Override
    public void deleteCategory(List<Integer> categoryIds) {
        log.debug("开始处理【删除活动分类】的请求,参数{}", categoryIds);
        if (CollectionUtils.isEmpty(categoryIds)) {
            throw new ServiceException("参数categoryIds不能为空");
        }
        Integer rows = activityMapper.deleteCategory(categoryIds);
        if (rows == 0) {
            throw new ServiceException("删除出错");
        }
        if (rows != categoryIds.size()) {
            throw new ServiceException("部分分类删除失败");
        }
    }

    @Override
    public void updateCategory(ActivityCategory activityCategory) {
        log.debug("开始处理【修改活动分类】的请求,参数{}", activityCategory);
        activityCategory.setCreateTime(new Date());
        Integer rows = activityMapper.updateCategory(activityCategory);
        if (rows == 0) {
            throw new ServiceException("修改失败");
        }
    }

    @Override
    public PageInfo<ActivityCategoryVO> listCategory(ActivityQuery query) {
        log.debug("开始处理【查询活动分类】的请求,参数{}", query);
        PageHelper.startPage(query.getPageNum(), query.getPageSize());
        List<ActivityCategoryVO> activityCategoryVOS = activityMapper.listCategory(query);
        return new PageInfo<>(activityCategoryVOS);
    }

    @Override
    public void join(ParticipationAddParam participation) {
        log.debug("开始处理【报名活动】的请求,参数{}", participation);

        // 参数校验
        if (participation.getUserId() == null || participation.getActivityId() == null) {
            throw new ServiceException("参数不完整");
        }

        // 获取活动详情
        ActivityVO activity = activityMapper.detail(participation.getActivityId());
        if (activity == null || activity.getStatus() != 1) { // 1表示已发布
            throw new ServiceException("活动不可报名");
        }

        // 检查是否已报名
        int count = activityMapper.countParticipation(
                participation.getActivityId(),
                participation.getUserId());
        if (count > 0) {
            throw new ServiceException("您已报名该活动");
        }

        // 检查人数限制
        if (activity.getMaxParticipants() != null &&
                activity.getCurrentParticipants() >= activity.getMaxParticipants()) {
            throw new ServiceException("活动人数已满");
        }

        // 创建报名记录
        ActivityParticipation join = new ActivityParticipation();
        join.setActivityId(participation.getActivityId());
        join.setUserId(participation.getUserId());
        join.setUserType(3); // 假设3是普通用户
        join.setSignupTime(new Date());
        join.setParticipationStatus(0); // 0表示已报名未签到
        join.setCreateTime(new Date());
        join.setUpdateTime(new Date());

        // 插入报名记录
        if (activityMapper.insertParticipation(join) != 1) {
            throw new ServiceException("报名失败，请稍后再试");
        }

        // 更新参与人数 (+1)
        activityMapper.incrementParticipants(participation.getActivityId(), 1);
    }

    @Override
    @Transactional
    public JsonResult checkIn(ParticipationAddParam participation) {
        User user = activityMapper.selectUserByUsername(participation.getUsername());
        if (user == null) {
            return new JsonResult(StatusCode.USER_NOT_EXIT, "用户不存在");
        }

        ActivityVO activity = activityMapper.selectActivityById(participation.getActivityId());
        if (activity == null) {
            return new JsonResult(StatusCode.FAILED, "活动不存在");
        }
        if (activity.getStatus() != 2) {
            return new JsonResult(StatusCode.FAILED, "活动当前不可签到");
        }

        // 检查是否已经签到过
        int participationStatus = activityMapper.getParticipationStatus(
                participation.getActivityId(),
                user.getUserId()
        );
        if (participationStatus == 1) { // 1表示已签到
            return JsonResult.ok("您已经签到过了");
        }

        ActivityUpdateParam param = new ActivityUpdateParam();
        param.setActivityId(participation.getActivityId());
        param.setUserId(user.getUserId());
        param.setStatus(1); // 1表示已签到

        int rows = activityMapper.updateParticipationStatus(param);
        if (rows == 0) {
            return new JsonResult(StatusCode.FAILED, "签到失败");
        }

        // 更新活动状态为已完成
        activityMapper.updateActivityStatus(participation.getActivityId(), 3); // 3表示已结束

        VolunteerInfoVO volunteerInfo = activityMapper.selectVolunteerInfoByUserId(user.getUserId());
        if (volunteerInfo != null) {
            activityMapper.incrementServiceHours(volunteerInfo.getVolunteerId(), 2.0);

            if (activity.getPointsAward() != null && activity.getPointsAward() > 0) {
                activityMapper.addPointsRecord(user.getUserId(),
                        activity.getPointsAward(),
                        1,
                        "活动参与奖励");
            }
        }

        return JsonResult.ok("签到成功");
    }
    @Override
    public void checkout(ParticipationCheckoutParam participation) {
        log.debug("开始处理【活动签退】的请求,参数:{}", participation);
        ActivityParticipation checkout = new ActivityParticipation();
        BeanUtils.copyProperties(participation, checkout);
        checkout.setCheckoutTime(new Date());
        checkout.setUpdateTime(new Date());
        // 更新活动状态为已完成
        activityMapper.updateActivityStatus(participation.getActivityId(), 4); // 3表示已结束
        Integer rows = activityMapper.checkout(checkout);
        if (rows != 1) {
            throw new ServiceException("活动签退失败，请稍后再试！");
        }
    }

    @Autowired
    private VolunteerMapper volunteerMapper;

    @Override
    public void confirmSchedule(Long scheduleId, Long userId) {
        // 验证排班记录是否存在
        VolunteerSchedule schedule = volunteerMapper.selectScheduleById(scheduleId);
        if (schedule == null) {
            throw new ServiceException(StatusCode.FAILED, "排班记录不存在");
        }

        // 验证用户是否有权限确认
        VolunteerInfo volunteer = volunteerMapper.selectByUserId(userId);
        if (volunteer == null || !volunteer.getVolunteerId().equals(schedule.getVolunteerId())) {
            throw new ServiceException(StatusCode.NO_PERMISSION, "无权操作此排班");
        }

        if (schedule.getStatus() != 0) {
            throw new ServiceException(StatusCode.FAILED, "排班状态不允许确认");
        }

        // 更新状态为已确认
        schedule.setStatus(1);
        volunteerMapper.updateByPrimaryKeySelective(schedule);
    }
}